package com.xssn.fjnd.contend.vodtest;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.apache.commons.lang.StringUtils;

/**
 * 说明：
 * 1. 本Demo为完整截图+修改封面逻辑设计，部分代码需要根据自己业务逻辑自行修改。
 * 2. 本Demo非直接可用，部分逻辑需要自行补充。
 * 3. 本Demo仅供实现参考，不代表唯一实现方式。
 */
public class SnapshotAndUpdateCover {

    // 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
    // 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
    // 本示例通过从环境变量中读取AccessKey，来实现API访问的身份验证。运行代码示例前，请配置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
    public static String accessKeyId = "LTAI5t8dyprRRh5rzP6kWuVc";
    public static String accessKeySecret = "8a1sYYmB1ctaLblN0XEIgi4NUS9EVX";
    public static void main(String[] args) {


        try{
            DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
            //视频ID
            String videoId = "d8211700436171eebf905420848c0102";

            //场景一：有回调服务 或 MNS
            //若是为新上传的视频设置封面，则需要先获取到音视频分析成功事件
            //若是为存量视频设置封面，则可以直接从此步骤开始提交截图任务
            submitSnapshotJob(vodClient,videoId);

            //获取到视频截图成功事件，判断截图类型，取得需要的图片URL
            JSONObject callBackMessage = new JSONObject();  //此处替换为回调服务收到的message
            String snapshotType = callBackMessage.getJSONObject("UserData").getJSONObject("Extend").getString("SnapshotType");
            if("FirstFrame".equals(snapshotType)){

                //这里的截图路径逻辑需要根据您自行定义的截图路径逻辑来替换
                String coverUrl = callBackMessage.getJSONArray("SnapshotInfos").getJSONObject(0).getString("SnapshotRegular").replace("{SnapshotCount}","00001");
                //修改视频封面
                System.out.println("coverUrl" + coverUrl);
                updateVideoInfo(vodClient,videoId,coverUrl);
            }

            //场景二：无回调服务 或 MNS
            //若是为新上传的视频设置封面，则视频上传后，轮询视频状态
            String videoStatus = "";
            while(!"Normal".equals(videoStatus)){
                videoStatus = getVideoInfo(vodClient,videoId);
                Thread.sleep(1000);
            }

            //若是为存量视频设置封面，则可以直接从此步骤开始提交截图任务
            submitSnapshotJob(vodClient,videoId);

            //轮询截图结果
            String coverUrl = "";
            while(StringUtils.isBlank(coverUrl)){
                coverUrl = listSnapshots(vodClient,videoId);
                System.out.println("coverUrl" + coverUrl);
                Thread.sleep(1000);
            }

            //修改视频封面
            updateVideoInfo(vodClient,videoId,coverUrl);
            System.out.println("coverUrl" + coverUrl);
        }catch (Exception e){

        }
    }

    /**
     * 提交截图任务
     */
    public static SubmitSnapshotJobResponse submitSnapshotJob(DefaultAcsClient vodClient, String vid) throws ClientException {
        SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
        request.setVideoId(vid);
        request.setSnapshotTemplateId("577fcc6d5a884f5994930b3a9c5553f2");
        //自定义透传参数，回调时可用，非必须，用于区分封面首帧截图
        request.setUserData("{\"Extend\":{\"SnapshotType\":\"FirstFrame\",\"VideoId\":\"a42bf540********33b79f0102\"}}");

        return vodClient.getAcsResponse(request);
    }

    /**
     * 修改视频封面
     */
    public static UpdateVideoInfoResponse updateVideoInfo(DefaultAcsClient vodClient, String vid, String coverUrl) throws ClientException {
        UpdateVideoInfoRequest request = new UpdateVideoInfoRequest();
        request.setVideoId(vid);
        //设置首帧封面时，CoverURL为首帧截图任务成功后输出的图片地址
        request.setCoverURL(coverUrl);

        return vodClient.getAcsResponse(request);
    }

    /**
     * 初始化sdk实例
     */
    public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
        // 点播服务接入区域
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        return client;
    }

    /**
     * 查询截图
     */
    public static String listSnapshots(DefaultAcsClient vodClient, String vid) throws ClientException {
        ListSnapshotsRequest request = new ListSnapshotsRequest();
        request.setVideoId(vid);
        request.setSnapshotType("NormalSnapshot");

        ListSnapshotsResponse response = vodClient.getAcsResponse(request);
        String coverUrl = "";
        System.out.println("RequestId is:" + response.getRequestId());
        try{
            coverUrl = response.getMediaSnapshot().getSnapshots().get(0).getUrl();
            System.out.println("SnapshotUrl is:" + response.getMediaSnapshot().getSnapshots().get(0).getUrl());
        }catch (NullPointerException e){

        }
        return coverUrl;
    }

    /**
     * 查询单个视频
     */
    public static String getVideoInfo(DefaultAcsClient vodClient, String vid) throws ClientException {
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        request.setVideoId(vid);

        GetVideoInfoResponse response = vodClient.getAcsResponse(request);
        System.out.println("RequestId is:" + response.getRequestId());
        String videoStatus = "";
        try{
            videoStatus = response.getVideo().getStatus();
            System.out.println("Video Status is:" + response.getVideo().getStatus());
        }catch (NullPointerException e){

        }

        return videoStatus;
    }
}
